package com.rbs.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rbs.common.Constants;
import com.rbs.entity.Department;
import org.springframework.web.bind.annotation.*;
import jakarta.annotation.Resource;
import com.rbs.common.Result;
import java.util.List;

import com.rbs.service.ICustomersService;
import com.rbs.entity.Customers;

import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 * 客户表 前端控制器
 * </p>
 *
 * @author lisl
 * @since 2024-04-24
 */
@RestController
@RequestMapping("/customers")
public class CustomersController {

    @Resource
    private ICustomersService customersService;

    //这个表我觉得简码允许重复比较好，所以我判断的是里面名字即中文是否重复
    //建议重复时，输入名字时，让那个人把当日日期加后面
    @PostMapping("/saveAndUpdate")
    public Result saveAndUpdate(@RequestBody Customers customers) {
        if (customers.getCStrcustomerid()!="") {
            boolean flag=customersService.findSameCustomerName(customers);
            if (flag==false){
                //客户名不存在，保存新的
                return Result.success(customersService.saveOrUpdate(customers));
            }else {
                //客户名存在
                return Result.error("客户名已经存在");
            }
        }else {
            return Result.error(Constants.CODE_400,"部门名不能为空！");
        }
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        return Result.success(customersService.removeById(id));
    }

    @PostMapping("/del/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        return Result.success(customersService.removeBatchByIds(ids));
    }

    //按名称模糊查询
    //传空值时返回全部
    @GetMapping("findByName")
    public Result findByName(@RequestBody Customers customers){
        List<Customers> cList=customersService.findByName(customers);
        return Result.success(cList);
    }

    @GetMapping
    public Result findAll() {
        return Result.success(customersService.list());
    }

    @GetMapping("/{id}")
    public Result findOne(@PathVariable Integer id) {
        return Result.success(customersService.getById(id));
    }

    //排序，分页给结果
    @GetMapping("/orderBy")
    public Result findPage(@RequestParam Integer pageNum,
                           @RequestParam Integer pageSize,
                           @RequestParam boolean descOrAsc,
                           @RequestParam String column) {
        //选哪一列来排序
        if (column.equals("cStrcustomerid"))column="C_strCustomerID";

        QueryWrapper<Customers> queryWrapper = new QueryWrapper<>();
        if (descOrAsc==true){
            queryWrapper.orderByDesc(column);
        }else if (descOrAsc==false){
            queryWrapper.orderByAsc(column);
        }
        return Result.success(customersService.page(new Page<>(pageNum, pageSize), queryWrapper));
    }
}

